package cn.bjc.org.service.impl;

import cn.bjc.basic.service.impl.BaseServiceImpl;
import cn.bjc.basic.util.Md5Utils;
import cn.bjc.basic.util.StrUtils;
import cn.bjc.org.domain.Employee;
import cn.bjc.org.mapper.EmployeeMapper;
import cn.bjc.org.service.IEmployeeService;
import cn.bjc.user.domain.Logininfo;
import cn.bjc.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
//将当前类自动注入到spring容器中
//声明将这个类有事务管理,父类有事务，该注解有继承性
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {
        //密码和盐值的生成与处理
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        
        //处理密码,加盐加密
        String dbPassword = Md5Utils.encrypByMd5((salt + employee.getPassword()));
        employee.setPassword(dbPassword);
        
        //将employee对象转成logininfo对象
        Logininfo logininfo = employee2logininfo(employee);
        //相同数据保存在logininfo表中
        logininfoMapper.save(logininfo);
        //获取自增长主键
        employee.setLogininfo_id(logininfo.getId());
        
        // 保存employee表
        employeeMapper.save(employee);  // 返回自增的主键
        
        // 保存中间表
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRole_id());
    }

    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void update(Employee employee) {

        super.update(employee);

        // 根据id删除t_employee_role
        employeeMapper.removeEmployeeRole(employee.getId());

        // 再加一波
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRole_id());

    }

    @Override
    public void remove(Long eid) {
        // 先删除t_employee_role
        employeeMapper.removeEmployeeRole(eid);

        employeeMapper.remove(eid);

    }

    @Override
    public List<Employee> findByShopId(long shopId) {
        return employeeMapper.findByShopId(shopId);
    }
}
